package com.zjw.server.service;

import com.alibaba.fastjson.JSONObject;
import com.zjw.model.R;
import com.zjw.model.enums.ClientType;
import com.zjw.model.pojo.vo.MessageVO;
import com.zjw.server.socket.SessionContainer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Service
public class MessageService {

    @Resource
    private SessionContainer sessionContainer;

    public R<Set<ClientType>> sendMessageToUser(MessageVO message) {
        String groupId = message.getGroupId();
        String to = message.getTo();
        if (StringUtils.isBlank(groupId)) {
            return R.fail("groupId不能为空");
        }
        if (StringUtils.isBlank(to)) {
            return R.fail("接受人不能为空");
        }
        Set<ClientType> clientTypes = new HashSet<>();
        Map<ClientType, Session> userAllSession = sessionContainer.getUserAllSession(groupId, to);
        userAllSession.forEach((clientType, session) -> {
            if (!sessionContainer.sendMessage(session, JSONObject.toJSONString(message))) {
                clientTypes.add(clientType);
            }
        });
        if (CollectionUtils.isEmpty(clientTypes)) {
            return R.ok();
        }
        return R.fail(clientTypes);
    }

    public R<Set<ClientType>> sendMessageToClientType(MessageVO message) {
        String groupId = message.getGroupId();
        String to = message.getTo();
        if (StringUtils.isBlank(groupId)) {
            return R.fail("groupId不能为空");
        }
        if (StringUtils.isBlank(to)) {
            return R.fail("接受人不能为空");
        }
        if (CollectionUtils.isEmpty(message.getClientTypes())) {
            return R.fail("接受人客户端类型不能为空");
        }
        Set<ClientType> clientTypes = new HashSet<>();
        Map<ClientType, Session> userAllSession = sessionContainer.getUserAllSession(message.getGroupId(), message.getTo());
        for (ClientType clientType : message.getClientTypes()) {
            Session session = userAllSession.get(clientType);
            if (session != null && sessionContainer.sendMessage(session, JSONObject.toJSONString(message))) {
                continue;
            }
            clientTypes.add(clientType);
        }
        if (CollectionUtils.isEmpty(clientTypes)) {
            return R.ok();
        }
        return R.fail(clientTypes);
    }
}
